package com.youlai.boot.core.tenant.filter;

import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.core.tenant.context.TenantContextHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 租户过滤器
 * 从 Spring Security 上下文中提取租户ID，设置到租户上下文
 * 
 * 此过滤器在 TokenAuthenticationFilter 之后执行，
 * 因此可以直接从 SecurityContext 中获取已认证的用户信息
 */
@Slf4j
@Component
public class TenantFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        try {
            // 从 Spring Security 上下文获取租户ID（最简洁的方式）
            Long tenantId = SecurityUtils.getTenantId();
            
            if (tenantId != null) {
                TenantContextHolder.setTenantId(tenantId);
                log.debug("租户过滤器: 设置租户ID = {}, 用户 = {}, URI = {}", 
                        tenantId, SecurityUtils.getUsername(), request.getRequestURI());
            }

            filterChain.doFilter(request, response);

        } finally {
            // 清理租户上下文（重要！）
            TenantContextHolder.clear();
        }
    }

    /**
     * 哪些路径不需要租户上下文
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();

        // 登录、验证码等接口不需要租户上下文
        return path.contains("/auth/login") ||
               path.contains("/auth/captcha") ||
               path.contains("/auth/refresh-token") ||
               path.contains("/swagger") ||
               path.contains("/v3/api-docs") ||
               path.contains("/doc.html");
    }
}
